/*
 * XMLDocumentBuilder.java
 *
 * Created on May 1, 2007, 5:15 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.plotnikov.pricemaker.xml;

import java.io.IOException;
import java.io.StringReader;
import org.plotnikov.pricemaker.utils.*;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author kostya
 */
public class XMLDocumentBuilder {
    
    private Element rootElement = null;
    private Document doc = null;
    private String rootName = "root";

    /** Creates a new instance of XMLDocumentBuilder */
    public XMLDocumentBuilder() {
    }

    public XMLDocumentBuilder(String rootname) {
        this.rootName = rootname;
    }
    
    public Document getDocument(){
        if(doc==null){
            try {
                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder;
                
                docBuilder = dbfac.newDocumentBuilder();
                doc = docBuilder.newDocument();

            } catch (ParserConfigurationException ex) {
                ex.printStackTrace();
            }            
        }
        return doc;
    }
    
    public Element getRootElement(){
        if(rootElement==null){
            rootElement = getDocument().createElement(rootName);
            getDocument().appendChild(rootElement);
        }
        return rootElement;
    }

    public boolean loadXML(String source){
        try {
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder;

            docBuilder = dbfac.newDocumentBuilder();
            doc = docBuilder.parse(new InputSource(new StringReader(source)));
            rootElement = doc.getDocumentElement();
            return true;
        } catch (SAXException ex) {
            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLDocumentBuilder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            ex.printStackTrace();
        }
        return false;
    }


    public Element createNodeFromDBEntity(Element parent, String name, DBEntity data){
        Element e = getDocument().createElement(name);
        for (int i = 0; i < data.getFieldCount(); i++) {
            DataChunk chunk = data.getFieldAt(i);
            String value = "";
            if(chunk.getData()!=null){
                if(chunk.getData() instanceof Date)
                    value = new SimpleDateFormat("dd.MM.yyyy").format((Date)chunk.getData());
                else
                    value = chunk.getData().toString();
            }
            e.setAttribute(chunk.getId(), value);
        }
        parent.appendChild(e);
        return e;
    }
    
    
    public Element createElement(String name){
        return getDocument().createElement(name);
    }

    
    public String makeXML(){
        return makeXML(getRootElement());
        
    }

    public String makeXML(Element root){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(getDocument());
            trans.transform(source, result);
            String xmlString = sw.toString();
            return xmlString;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return "";
    }
    
    public String makeXSLTransform(String xslPath){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Templates template = 
                    transfac.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslPath)));
            Transformer trans = template.newTransformer();
            
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(getDocument());
            trans.transform(source, result);
            String xmlString = sw.toString();
            
            return xmlString;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return "";        
    }
    
    public String makeXSLTransform(String xslPath, String[][] attrs){
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Templates template = 
                    transfac.newTemplates(new StreamSource(this.getClass().getResourceAsStream(xslPath)));
            Transformer trans = template.newTransformer();
            
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            
            for (int i = 0; i < attrs.length; i++) {
                if (attrs[i][0]!=null && !attrs.equals("")){
                    trans.setParameter(attrs[i][0], attrs[i][1]==null?"":attrs[i][1]);
                }
            }
            
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(getDocument());
            trans.transform(source, result);
            String xmlString = sw.toString();
            
            return xmlString;
        } catch (Throwable t) {
            t.printStackTrace();
        }    
        return "";        
    }
    
}
